######################################################################
######################################################################
# Replication Code for Long Form Appendix of: 
# Woldense and Kroeger. Elite Change without Regime Change:
# Authoritarian Persistence in Africa and the End of the 
# Cold War. American Political Science Review. 
######################################################################
######################################################################


#The code below replicates the analyses, figures, and tables in the 
#in the long form appendix. 

#Windows users must first install Rtools
#See: https://cran.r-project.org/bin/windows/Rtools/rtools42/rtools.html

#Install devtools package to install previous versions of Zelig and stargazer
install.packages('devtools')
library(devtools)


#install last version of Zelig (before it was
#removed from CRAN) and its dependencies
install_version('Zelig', version = '5.1.7',
                repos = "http://cran.us.r-project.org",
                dependencies = TRUE)

#install pacman to check if other needed packages
#are installed, install any missing packages, 
#and load all packages
install.packages('pacman')

pacman::p_load(multiwayvcov, lmtest, xtable, texreg, 
               margins, survival, car, ggpubr, 
               zoo, tidyverse)

#install previous version of stargazer 
#current version is not compatible with the code
#below
install_version('stargazer', version = '5.2.2', 
                repos = "http://cran.us.r-project.org")

#load stargazer and Zelig
library(stargazer)
library(Zelig)



#load full dataset
df <- read.csv("Woldense_Kroeger_APSR.csv")


#Main GWF sub-Saharan Data Sample ------------------------------------------------------------

#list of countries to omit for main sub-Saharan analyses, includes 
#south africa under apartheid 
nafrica_sa <- c('Morocco','Algeria','Tunisia','Libya','Egypt','South Africa')

gwf_ssa <- df %>%
  filter(!is.na(gwf_regimetype)) %>%
  filter(!(country_name %in% nafrica_sa))




# Section A2 Tables  -------------------------------------------------------------


#function for displaying country-years in sample
cy_table <- function(x){
  
  x %>%
    group_by(country_name) %>%
    #identify breaks in authoritarianism
    mutate(year_l = dplyr::lag(year, n = 1L), 
           year_l = ifelse(is.na(year_l), year - 1, year_l),
           gap = ifelse(year - year_l > 1, 1, 0), 
           spell = cumsum(gap)) %>%
    group_by(country_name, spell) %>%
    summarise(country_name = first(country_name), 
              start_year = min(year),
              end_year = max(year)) %>%
    dplyr::select(-spell)
}

#summary statistics function
summary_table <- function(x){
  x %>%
    dplyr::select(spell_end, 
                  CWE_5, 
                  minister_tenure,
                  senior,
                  high_prestige,
                  leader_tenure, 
                  leader_exit, 
                  pers_2pl, 
                  election_corrected,
                  coup_corrected,
                  lcgdppc,
                  ln_oilgas_rents, 
                  ln_total_aid_AD,
                  v2x_polyarchy, 
                  cabinet_size,
                  left_truncated)
}


# Main GWF SSA Sample Summary Statistics 

gwf_ssa_table <- cy_table(gwf_ssa)

#Table A3
print(xtable(gwf_ssa_table, 
             caption = 'GWF Autocracy, sub-Saharan Sample Country-Years'),
      include.rownames = FALSE,
      type = 'latex',
      tabular.environment = 'longtable',
      floating = FALSE,
      caption.placement = 'top', 
      file = 'gwf_ssa_sample.tex')

gwf_ssa_summary <- summary_table(gwf_ssa)

#Table A2
stargazer(gwf_ssa_summary, 
          covariate.labels = c('Minister Exit', 
                               'CWE 5-year', 
                               'Minister Tenure',
                               'Senior Minister',
                               'High Prestige Portfolio',
                               'Leader Tenure', 
                               'Leader Exit',
                               'Personalism',
                               'Election', 
                               'Failed Coup',
                               'Ln(GDP per Capita)',
                               'Cabinet Size',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Left Truncated'),
          table.placement = '!hbt',
          digits = 2,
          title = 'GWF Autocracy, sub-Saharan Sample Summary Statistics', 
          out = 'gwf_ssa_stats.tex')


# GWF All Africa Sample Summary Statistics

gwf_all <- df %>%
  filter(!is.na(gwf_regimetype))

gwf_all_table <- cy_table(gwf_all)

#Table A5
print(xtable(gwf_all_table, 
             caption = 'GWF Autocracy, All Africa Sample Country-Years'),
      include.rownames = FALSE,
      type = 'latex',
      tabular.environment = 'longtable',
      floating = FALSE,
      caption.placement = 'top', 
      file = 'gwf_all_sample.tex')

gwf_all_summary <- summary_table(gwf_all)

#Table A4
stargazer(gwf_all_summary, 
          covariate.labels = c('Minister Exit', 
                               'CWE 5-year', 
                               'Minister Tenure',
                               'Senior Minister',
                               'High Prestige Portfolio',
                               'Leader Tenure', 
                               'Leader Exit',
                               'Personalism',
                               'Election', 
                               'Failed Coup',
                               'Ln(GDP per Capita)',
                               'Cabinet Size',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Left Truncated'),
          table.placement = '!hbt',
          digits = 2,
          title = 'GWF Autocracy, All Africa Sample Summary Statistics', 
          out = 'gwf_all_stats.tex')


# Lexical Index of Electoral Democracy sub-Saharan Sample Summary Statistics

lied_ssa <- df %>%
  filter(lied_autoc==1) %>%
  filter(!(country_name %in% nafrica_sa))

lied_ssa_table <- cy_table(lied_ssa) 

print(xtable(lied_ssa_table, 
             caption = 'LIED Autocracy, sub-Saharan Sample Country-Years'),
      include.rownames = FALSE,
      type = 'latex',
      tabular.environment = 'longtable',
      floating = FALSE,
      caption.placement = 'top', 
      file = 'lied_ssa_sample.tex')

lied_ssa_summary <- summary_table(lied_ssa)

stargazer(lied_ssa_summary, 
          covariate.labels = c('Minister Exit', 
                               'CWE 5-year', 
                               'Minister Tenure',
                               'Senior Minister',
                               'High Prestige Portfolio',
                               'Leader Tenure', 
                               'Leader Exit',
                               'Personalism',
                               'Election', 
                               'Failed Coup',
                               'Ln(GDP per Capita)',
                               'Cabinet Size',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Left Truncated'),
          table.placement = '!hbt',
          digits = 2,
          title = 'LIED Autocracy, sub-Saharan Sample Summary Statistics', 
          out = 'lied_ssa_stats.tex')


# Lexical Index of Electoral Democracy All Africa Sample Summary Statistics

lied_all <- df %>%
  filter(lied_autoc==1) 

lied_all_table <- cy_table(lied_all)

print(xtable(lied_all_table, 
             caption = 'LIED Autocracy, All Africa Sample Country-Years'),
      include.rownames = FALSE,
      type = 'latex',
      tabular.environment = 'longtable',
      floating = FALSE,
      caption.placement = 'top', 
      file = 'lied_all_sample.tex')

lied_all_summary <- summary_table(lied_all)

stargazer(lied_all_summary, 
          covariate.labels = c('Minister Exit', 
                               'CWE 5-year', 
                               'Minister Tenure',
                               'Senior Minister',
                               'High Prestige Portfolio',
                               'Leader Tenure', 
                               'Leader Exit',
                               'Personalism',
                               'Election', 
                               'Failed Coup',
                               'Ln(GDP per Capita)',
                               'Cabinet Size',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Left Truncated'),
          table.placement = '!hbt',
          digits = 2,
          title = 'LIED Autocracy, All Africa Sample Summary Statistics', 
          out = 'lied_all_stats.tex')



# VDem ROW sub-Saharan Sample Summary Statistics 

row_ssa <- df %>%
  filter(vdem_autoc==1) %>%
  filter(!(country_name %in% nafrica_sa))

row_ssa_table <- cy_table(row_ssa)

print(xtable(row_ssa_table, 
             caption = 'VDem ROW Autocracy, sub-Saharan Sample Country-Years'),
      include.rownames = FALSE,
      type = 'latex',
      tabular.environment = 'longtable',
      floating = FALSE,
      caption.placement = 'top', 
      file = 'row_ssa_sample.tex')

row_ssa_summary <- summary_table(row_ssa)

stargazer(row_ssa_summary, 
          covariate.labels = c('Minister Exit', 
                               'CWE 5-year', 
                               'Minister Tenure',
                               'Senior Minister',
                               'High Prestige Portfolio',
                               'Leader Tenure', 
                               'Leader Exit',
                               'Personalism',
                               'Election', 
                               'Failed Coup',
                               'Ln(GDP per Capita)',
                               'Cabinet Size',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Left Truncated'),
          table.placement = '!hbt',
          digits = 2,
          title = 'VDem ROW Autocracy, sub-Saharan Sample Summary Statistics', 
          out = 'row_ssa_stats.tex')


# VDem ROW All Africa Sample Summary Statistics 

row_all <- df %>%
  filter(vdem_autoc==1) 

row_all_table <- cy_table(row_all)

print(xtable(row_all_table, 
             caption = 'VDem ROW Autocracy, All Africa Sample Country-Years'),
      include.rownames = FALSE,
      type = 'latex',
      tabular.environment = 'longtable',
      floating = FALSE,
      caption.placement = 'top', 
      file = 'row_all_sample.tex')

row_all_summary <- summary_table(row_all)

stargazer(row_all_summary, 
          covariate.labels = c('Minister Exit', 
                               'CWE 5-year', 
                               'Minister Tenure',
                               'Senior Minister',
                               'High Prestige Portfolio',
                               'Leader Tenure', 
                               'Leader Exit',
                               'Personalism',
                               'Election', 
                               'Failed Coup',
                               'Ln(GDP per Capita)',
                               'Cabinet Size',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Left Truncated'),
          table.placement = '!hbt',
          digits = 2,
          title = 'VDem ROW Autocracy, All Africa Sample Summary Statistics', 
          out = 'row_all_stats.tex')


# Balanced sub-Saharan Sample Summary Statistics 

#find continuous cases of autocracy using gwf_ssa sample 
#cwe start = 1988, cwe end = 1992

ssa_balance_remove <- c('Morocco','Algeria','Tunisia','Libya','Egypt','South Africa',
                        'Namibia', 'Somalia')

gwf_ssa_cw_regimes <- df %>%
  filter(!(country_name %in% ssa_balance_remove)) %>%
  mutate(cold_war = ifelse(year < 1988, 1, 0), 
         gwf_dictatorship = ifelse(!is.na(gwf_regimetype), 1, 0)) %>%
  filter(cold_war==1) %>%
  group_by(cowcode) %>%
  mutate(dictatorship_percent = mean(gwf_dictatorship)) 

gwf_always <- gwf_ssa_cw_regimes %>%
  filter(dictatorship_percent==1) %>%
  group_by(cowcode) %>%
  summarize(country_name = first(country_name)) %>%
  pull(cowcode)

gwf_ssa_balanced <- df %>%
  #select countries that had uninterrupted autocratic spells (not necessarily same regime)
  #going into the cwe period
  filter(cowcode %in% gwf_always & cowcode != 553| #malawi excluded because of missing 1983 data
           #benin post 1972
           cowcode==434 & year > 1972| 
           #sierra leone post 1966
           cowcode==451 & year > 1966| 
           #ghana post 1981
           cowcode==452 & year > 1981| 
           #nigeria post 1983
           cowcode==475 & year > 1983| 
           #chad post 1981
           cowcode==483 & year > 1981| 
           #uganda post 1980
           cowcode==500 & year > 1980| 
           #angola post 1975
           cowcode==540 & year > 1975| 
           #zambia post 1966
           cowcode==551 & year > 1966| 
           #lesotho after 1969
           cowcode==570 & year > 1969) %>%
  filter(year < 2011)


gwf_ssa_balanced_table <- cy_table(gwf_ssa_balanced)

#Table A14
print(xtable(gwf_ssa_balanced_table, 
             caption = 'GWF Autocracy, sub-Saharan Balanced Sample'),
      include.rownames = FALSE,
      type = 'latex',
      tabular.environment = 'longtable',
      floating = FALSE,
      caption.placement = 'top', 
      file = 'gwf_ssa_balanced_sample.tex')

#Table A15
gwf_ssa_balanced_summary <- summary_table(gwf_ssa_balanced)

stargazer(gwf_ssa_balanced_summary, 
          covariate.labels = c('Minister Exit', 
                               'CWE 5-year', 
                               'Minister Tenure',
                               'Senior Minister',
                               'High Prestige Portfolio',
                               'Leader Tenure', 
                               'Leader Exit',
                               'Personalism',
                               'Election', 
                               'Failed Coup',
                               'Ln(GDP per Capita)',
                               'Cabinet Size',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Left Truncated'),
          table.placement = '!hbt',
          digits = 2,
          title = 'GWF Autocracy, sub-Saharan Balanced Sample Summary Statistics', 
          out = 'gwf_ssa_balanced_stats.tex')




# Country-Years and Minister-Years in All Samples 

#list of all samples
samples <- list(gwf_ssa, gwf_all, 
                lied_ssa, lied_all,
                row_ssa, row_all)


cy_snapshot <- function(x){
  
  country_years <- x %>%
    dplyr::select(cowcode, year) %>%
    group_by(cowcode, year) %>%
    summarise_all(first) %>%
    ungroup() %>%
    summarise(Countries = n_distinct(cowcode), 
              `Country-years` = n())
  
  minister_years <- x %>%
    dplyr::select(ministerID, year) %>%
    group_by(ministerID, year) %>%
    summarise_all(first) %>%
    ungroup() %>%
    summarise(Ministers = n_distinct(ministerID),
              `Minister-years` = n())
  
  bind_cols(country_years, minister_years)
}

samples_snapshot <- lapply(samples, cy_snapshot) %>%
  bind_rows(.) %>%
  mutate(Sample = c('GWF sub-Saharan (Main)', 'GWF All', 
                    'LIED sub-Saharan', 'LIED All', 
                    'VDem ROW sub-Saharan', 'VDem ROW All'))%>%
  dplyr::select(Sample, Countries, `Country-years`, 
                Ministers, `Minister-years`)

#Table A1
stargazer(samples_snapshot, 
          summary = F, 
          rownames = F,
          table.placement = '!hbt',
          title = 'Summary of Countries and Ministers across Sample Variations',
          out = 'samples_snapshot.tex')



# Country-Year Data 

cy <- read.csv('Woldense_Kroeger_APSR_CY.csv')



# Section A3 Models -------------------------------------------------------

#function to apply pooled logit models across data samples

samples_pooled_logit <- function(xvar, controls){
  
  lapply(samples, function(y){
    
    model <- glm(as.formula(paste('spell_end ~', 
                                  xvar, controls)), 
                 data = y, 
                 family = binomial)
    
    
    SEs <- sqrt(diag(cluster.vcov(model, y$leaderID)))
    
    return(list(model, SEs))
    
  })
}



#CWE_5 pooled models across all samples

#Table A17, no controls
A17 <- samples_pooled_logit('CWE_5', none)


#no controls table of results
stargazer(A17[[1]][[1]], A17[[2]][[1]], 
          A17[[3]][[1]], A17[[4]][[1]], 
          A17[[5]][[1]], A17[[6]][[1]], 
          se = list(A17[[1]][[2]], A17[[2]][[2]], 
                    A17[[3]][[2]], A17[[4]][[2]], 
                    A17[[5]][[2]], A17[[6]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels = ' &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          covariate.labels = 'CWE 5-year',
          omit.stat = c('ll', 'aic'),
          digits = 2,
          no.space = T,
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, No Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe5_pooled_none',
          out = 'cwe5_pooled_none.tex')


#Table A18, baseline controls
A18 <- samples_pooled_logit('CWE_5', baseline)

#baseline table of results
stargazer(A18[[1]][[1]], A18[[2]][[1]], 
          A18[[3]][[1]], A18[[4]][[1]], 
          A18[[5]][[1]], A18[[6]][[1]], 
          se = list(A18[[1]][[2]], A18[[2]][[2]], 
                    A18[[3]][[2]], A18[[4]][[2]], 
                    A18[[5]][[2]], A18[[6]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_pooled_baseline',
          covariate.labels = c('CWE 5-year', 'Ln(Oil/Gas Rents)',
                               'Personalism', 'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          omit.stat = c('ll', 'aic'),
          digits = 2,
          no.space = TRUE,
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, Baseline Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_pooled_baseline.tex')


#Table A19, tenure controls

A19 <- samples_pooled_logit('CWE_5', tenure)

#tenure table of results
stargazer(A19[[1]][[1]], A19[[2]][[1]], 
          A19[[3]][[1]], A19[[4]][[1]], 
          A19[[5]][[1]], A19[[6]][[1]], 
          se = list(A19[[1]][[2]], A19[[2]][[2]], 
                    A19[[3]][[2]], A19[[4]][[2]], 
                    A19[[5]][[2]], A19[[6]][[2]]), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_pooled_tenure',
          omit.stat = c('ll', 'aic'),
          digits = 2,
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, Tenure Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_pooled_tenure.tex')


#Table A20, event controls

A20 <- samples_pooled_logit('CWE_5', events)

stargazer(A20[[1]][[1]], A20[[2]][[1]], 
          A20[[3]][[1]], A20[[4]][[1]], 
          A20[[5]][[1]], A20[[6]][[1]], 
          se = list(A20[[1]][[2]], A20[[2]][[2]], 
                    A20[[3]][[2]], A20[[4]][[2]], 
                    A20[[5]][[2]], A20[[6]][[2]]), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_pooled_events',
          omit.stat = c('ll', 'aic'),
          digits = 2,
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, Events Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_pooled_events.tex')


#Table A21, aid and vdem polyarchy added

A21 <- samples_pooled_logit('CWE_5', aid_dem)

stargazer(A21[[1]][[1]], A21[[2]][[1]], 
          A21[[3]][[1]], A21[[4]][[1]], 
          A21[[5]][[1]], A21[[6]][[1]], 
          se = list(A21[[1]][[2]], A21[[2]][[2]], 
                    A21[[3]][[2]], A21[[4]][[2]], 
                    A21[[5]][[2]], A21[[6]][[2]]), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_pooled_extras',
          omit.stat = c('ll', 'aic'),
          digits = 2,
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)', 
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, Additional Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_pooled_extras.tex')



#conditional logit model across samples function (leader fixed effects)

fe_logit <- function(xvar, controls){
  
  lapply(samples, function(y){
    
    clogit(as.formula(paste0('spell_end ~', xvar, paste0(controls),
                             '+ strata(leaderID)')), 
           data = y, 
           method = 'efron',
           cluster = leaderID)
    
    
  })
}



#5 year window,  across samples

#no controls
A22 <- fe_logit('CWE_5', none)

A22_results <- lapply(A22, broom::tidy)

stargazer(A22[[1]], 
          A22[[2]], 
          A22[[3]], 
          A22[[4]], 
          A22[[5]], 
          A22[[6]],
          coef = list(A22_results[[1]]$estimate, 
                      A22_results[[2]]$estimate, 
                      A22_results[[3]]$estimate, 
                      A22_results[[4]]$estimate, 
                      A22_results[[5]]$estimate, 
                      A22_results[[6]]$estimate), 
          se = list(A22_results[[1]]$robust.se, 
                    A22_results[[2]]$robust.se, 
                    A22_results[[3]]$robust.se, 
                    A22_results[[4]]$robust.se, 
                    A22_results[[5]]$robust.se, 
                    A22_results[[6]]$robust.se),
          table.placement = '!hbt',
          
          dep.var.labels.include = F,
          dep.var.caption = '',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          covariate.labels = 'CWE 5-year',
          label = 'tab:cwe5_fe_none',
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          add.lines=list(c('Leader fixed effects', 'Yes','Yes', 'Yes', 
                           'Yes', 'Yes', 'Yes')),
          digits = 2,
          no.space = T,
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, No Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_fe_none.tex')


#baseline controls
A23 <- fe_logit('CWE_5', baseline)

A23_results <- lapply(A23, broom::tidy)


stargazer(A23[[1]], 
          A23[[2]], 
          A23[[3]], 
          A23[[4]], 
          A23[[5]], 
          A23[[6]],
          coef = list(A23_results[[1]]$estimate, 
                      A23_results[[2]]$estimate, 
                      A23_results[[3]]$estimate, 
                      A23_results[[4]]$estimate, 
                      A23_results[[5]]$estimate, 
                      A23_results[[6]]$estimate), 
          se = list(A23_results[[1]]$robust.se, 
                    A23_results[[2]]$robust.se, 
                    A23_results[[3]]$robust.se, 
                    A23_results[[4]]$robust.se, 
                    A23_results[[5]]$robust.se, 
                    A23_results[[6]]$robust.se),
          table.placement = '!hbt',
          
          dep.var.labels.include = F,
          dep.var.caption = '',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_fe_baseline',
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          covariate.labels = c('CWE 5-year', 'Ln(Oil/Gas Rents)',
                               'Personalism', 'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          add.lines=list(c('Leader fixed effects', 'Yes','Yes', 'Yes', 
                           'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Baseline Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_fe_baseline.tex')






#tenure controls
A24 <- fe_logit('CWE_5', tenure)

A24_results <- lapply(A24, broom::tidy)

stargazer(A24[[1]], 
          A24[[2]], 
          A24[[3]], 
          A24[[4]], 
          A24[[5]], 
          A24[[6]],
          coef = list(A24_results[[1]]$estimate, 
                      A24_results[[2]]$estimate, 
                      A24_results[[3]]$estimate, 
                      A24_results[[4]]$estimate, 
                      A24_results[[5]]$estimate, 
                      A24_results[[6]]$estimate), 
          se = list(A24_results[[1]]$robust.se, 
                    A24_results[[2]]$robust.se, 
                    A24_results[[3]]$robust.se, 
                    A24_results[[4]]$robust.se, 
                    A24_results[[5]]$robust.se, 
                    A24_results[[6]]$robust.se),
          table.placement = '!hbt',
          
          dep.var.labels.include = F,
          dep.var.caption = '',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_fe_tenure',
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          add.lines=list(c('Leader fixed effects', 'Yes','Yes', 'Yes', 
                           'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Tenure Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_fe_tenure.tex')


#event controls
A25 <- fe_logit('CWE_5', events)

A25_results <- lapply(A25, broom::tidy)


stargazer(A25[[1]], 
          A25[[2]], 
          A25[[3]], 
          A25[[4]], 
          A25[[5]], 
          A25[[6]],
          coef = list(A25_results[[1]]$estimate, 
                      A25_results[[2]]$estimate, 
                      A25_results[[3]]$estimate, 
                      A25_results[[4]]$estimate, 
                      A25_results[[5]]$estimate, 
                      A25_results[[6]]$estimate), 
          se = list(A25_results[[1]]$robust.se, 
                    A25_results[[2]]$robust.se, 
                    A25_results[[3]]$robust.se, 
                    A25_results[[4]]$robust.se, 
                    A25_results[[5]]$robust.se, 
                    A25_results[[6]]$robust.se),
          table.placement = '!hbt',
          
          dep.var.labels.include = F,
          dep.var.caption = '',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_fe_none',
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          add.lines=list(c('Leader fixed effects', 'Yes','Yes', 'Yes', 
                           'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Events Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_fe_events.tex')


#extra controls

A26 <- fe_logit('CWE_5', aid_dem)

A26_results <- lapply(A26, broom::tidy)


stargazer(A26[[1]], 
          A26[[2]], 
          A26[[3]], 
          A26[[4]], 
          A26[[5]], 
          A26[[6]],
          coef = list(A26_results[[1]]$estimate, 
                      A26_results[[2]]$estimate, 
                      A26_results[[3]]$estimate, 
                      A26_results[[4]]$estimate, 
                      A26_results[[5]]$estimate, 
                      A26_results[[6]]$estimate), 
          se = list(A26_results[[1]]$robust.se, 
                    A26_results[[2]]$robust.se, 
                    A26_results[[3]]$robust.se, 
                    A26_results[[4]]$robust.se, 
                    A26_results[[5]]$robust.se, 
                    A26_results[[6]]$robust.se),
          table.placement = '!hbt',
          
          dep.var.labels.include = F,
          dep.var.caption = '',
          column.labels = '  &  & &  & VDem & VDem \\\\
& GWF & GWF & LIED & LIED & ROW & ROW \\\\
&    SSA     &  All     &    SSA    &   All  &     SSA     & All\\\\',
          label = 'tab:cwe5_fe_extras',
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)', 
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          add.lines=list(c('Leader fixed effects', 'Yes','Yes', 'Yes', 
                           'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Additional Controls', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_fe_extras.tex')



#A3.3 Pooled models using balanced GWF SSA sample 

pooled_balanced_logit <- function(xvar, controls){
  
  model <- glm(as.formula(paste('spell_end ~', 
                                xvar, controls)), 
               data = gwf_ssa_balanced, 
               family = binomial)
  
  SEs <- sqrt(diag(cluster.vcov(model, gwf_ssa_balanced$leaderID)))
  
  return(list(model, SEs))
  
}

#Table A27 models
#no controls
A27_none <- pooled_balanced_logit('CWE_5', none)

#baseline controls
A27_base <- pooled_balanced_logit('CWE_5', baseline)

#tenure controls
A27_tenure <- pooled_balanced_logit('CWE_5', tenure)

#events controls
A27_events <- pooled_balanced_logit('CWE_5', events)

#Table A27
stargazer(A27_none[[1]],
          A27_base[[1]],
          A27_tenure[[1]],
          A27_events[[1]],
          se = list(A27_none[[2]],
                    A27_base[[2]],
                    A27_tenure[[2]],
                    A27_events[[2]]),
          dep.var.labels.include = F,
          dep.var.caption = '',
          column.labels = c('No Controls',
                            'Baseline',
                            'Tenure',
                            'Events'),
          label = 'tab:cwe5_pooled_balanced',
          table.placement = '!hbt',
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          omit.stat =  c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                         'lr', 'wald'),
          digits = 2,
          no.space = T,
          title = 'Pooled Models of Minister Survival with 5-year CWE Window, Balanced Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001),
          out = 'cwe5_pooled_balanced.tex')


#Leader fixed effects models using GWF SSA balanced sample

fe_balanced_logit <- function(xvar, controls){
  
  
  clogit(as.formula(paste0('spell_end ~', xvar, paste0(controls),
                           '+ strata(leaderID)')), 
         data = gwf_ssa_balanced, 
         method = 'efron',
         cluster = leaderID)
  
  
}

#no controls
A28_fe_none <- fe_balanced_logit('CWE_5', none)

#baseline controls
A28_fe_base <- fe_balanced_logit('CWE_5', baseline)

#tenure controls
A28_fe_tenure <- fe_balanced_logit('CWE_5', tenure)

#events controls
A28_fe_events <- fe_balanced_logit('CWE_5', events)



stargazer(A28_fe_none, A28_fe_base, 
          A28_fe_tenure, A28_fe_events, 
          coef = list(A28_fe_none$coefficients,
                      A28_fe_base$coefficients,
                      A28_fe_tenure$coefficients,
                      A28_fe_events$coefficients),
          se = list(sqrt(diag(A28_fe_none$var)),
                    sqrt(diag(A28_fe_base$var)),
                    sqrt(diag(A28_fe_tenure$var)),
                    sqrt(diag(A28_fe_events$var))),
          table.placement = '!hbt',
          dep.var.labels.include = F,
          dep.var.caption = '',
          column.labels = c('No Controls',
                            'Baseline',
                            'Tenure',
                            'Events'),
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          label = 'tab:cwe5_fe_balanced',
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          add.lines=list(c('Leader fixed effects?', 'Yes','Yes', 'Yes', 
                           'Yes')),
          digits = 2,
          no.space = T,
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Balanced Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_fe_balanced.tex')




#A3.4 Pooled models using data only from CWE surviving leaders

#find cwe surviving leaders
survivors <- gwf_ssa %>%
  dplyr::select(leader_name, leaderID, country_name, year, CWE_5) %>%
  group_by(leaderID, year) %>%
  summarise_all(first) %>%
  group_by(leaderID) %>%
  mutate(leader_start = first(year), 
         leader_end = last(year)) %>%
  #select only leaders with at least three years of data before and
  #after CWE window. Any less will probably not satisfy reviewers.
  filter(leader_start < 1985,
         leader_end > 1995) %>%
  summarise_all(first)  


survivors_table <- survivors %>%
  dplyr::select(country_name, leader_name, leader_start, leader_end) %>%
  rename(Country = country_name, 
         Leader = leader_name, 
         Start = leader_start, 
         End = leader_end) %>%
  arrange(Country)

#Table A16
stargazer(survivors_table, 
          summary = F,
          rownames = F,
          title = 'CWE Surviving Leaders, GWF SSA Sample',
          notes = 'Note: Leader start and end years reflect cabinet observations in our dataset.',
          out = 'cwe_survivors.tex')



#save surviving leader ids to filter gwf_ssa data
survivor_ids <- survivors$leaderID

gwf_ssa_survivors <- gwf_ssa %>%
  filter(leaderID %in% survivor_ids)


#survivors pooled model function

pooled_logit_survivors <- function(controls, data_sample){
  
  model <- glm(as.formula(paste('spell_end ~ CWE_5', controls)), 
               data = data_sample, 
               family = binomial)
  
  
  SEs <- sqrt(diag(cluster.vcov(model, data_sample$leaderID)))
  
  clustered_vcov <- cluster.vcov(model, data_sample$leaderID)
  
  margins_df <- data.frame(summary(margins(model, vcov = clustered_vcov)))
  
  return(list(model, SEs, margins_df))
  
}

#Table A29 models
#pooled model with no controls

A29_none <- pooled_logit_survivors(none, gwf_ssa_survivors)

#pooled model with baseline controls

A29_baseline <- pooled_logit_survivors(baseline, gwf_ssa_survivors)

#pooled model with tenure controls

A29_tenure <- pooled_logit_survivors(tenure, gwf_ssa_survivors)

#pooled model with event controls

A29_events <- pooled_logit_survivors(events, gwf_ssa_survivors)

#Table A29, results for survivor pooled models

stargazer(A29_none[[1]], A29_baseline[[1]], 
          A29_tenure[[1]], A29_events[[1]], 
          se = list(A29_none[[2]], 
                    A29_baseline[[2]], 
                    A29_tenure[[2]], 
                    A29_events[[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels = c('No Controls', 'Baseline', 
                            'Tenure', 'Events'),
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival, GWF SSA Sample Limited to CWE Surviving Leaders', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'survivors_pooled.tex')


#survivors leader fixed effects function

fe_logit_survivors <- function(controls, data_sample){
  
  clogit(as.formula(paste0('spell_end ~ CWE_5', paste0(controls),
                           '+ strata(leaderID)')), 
         data = data_sample, 
         method = 'efron',
         cluster = leaderID)
}

#fe model no controls

A30_none <- fe_logit_survivors(none, gwf_ssa_survivors)

A30_none_se <- broom::tidy(A30_none)$robust.se

#fe model baseline controls

A30_baseline <- fe_logit_survivors(baseline, gwf_ssa_survivors)

A30_baseline_se <- broom::tidy(A30_baseline)$robust.se

#fe model tenure controls

A30_tenure <- fe_logit_survivors(tenure, gwf_ssa_survivors)

A30_tenure_se <- broom::tidy(A30_tenure)$robust.se

#fe model events controls

A30_events <- fe_logit_survivors(events, gwf_ssa_survivors)

A30_events_se <- broom::tidy(A30_events)$robust.se


stargazer(A30_none, A30_baseline, 
          A30_tenure, A30_events,
          se = list(A30_none_se, 
                    A30_baseline_se, 
                    A30_tenure_se, 
                    A30_events_se),
          table.placement = '!hbt',
          column.labels = c('No Controls', 'Baseline', 
                            'Tenure', 'Events'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          dep.var.labels = 'Minister Exit',
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival, GWF SSA Sample Limited to CWE Surviving Leaders', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'survivors_fe.tex')




# Section A4 Models -------------------------------------------------------

#Pooled logit models with senior dummy by CWE window interaction
senior_pooled_logit <- function(xvar){
  
  senior_df <- gwf_ssa %>%
    mutate(cwe_option = !!sym(xvar))
  
  glm(spell_end ~ cwe_option*senior + 
        ln_oilgas_rents +
        pers_2pl +
        leader_exit + 
        leader_tenure +
        I(leader_tenure^2) +
        I(leader_tenure^3) +
        election_corrected + 
        coup_corrected + 
        lcgdppc + 
        cabinet_size + 
        left_truncated,
      data = senior_df, 
      family = binomial)
}

#Table A31 models
A31 <- lapply(cwe_options, senior_pooled_logit)


#Table A31
stargazer(A31[[1]], A31[[2]],
          A31[[3]], A31[[4]],
          A31[[5]], 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('CWE 5-year', 'CWE 4-year', 
                             'CWE 3-year', 'CWE 2-year',
                             'CWE 1-year'), 
          order = c(1, 2, 14, 3, 4, 5, 6, 7, 
                    8, 9, 10, 11, 12, 13),
          digits = 2,
          covariate.labels = c('CWE Window', 
                               'Senior Minister',
                               'CWE X Senior',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 
                               'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit Models with Senior Minister by CWE Interaction from Figure 5', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe_senior_pooled.tex')


#Figure A1: Marginal effects for pooled logit models on senior minister only sample


gwf_ssa_senior <- gwf_ssa %>%
  filter(senior==1)

#senior model formulas

tenure_senior <- ' + ln_oilgas_rents + 
                    pers_2pl +
                    leader_tenure +
                    I(leader_tenure^2) +
                    I(leader_tenure^3) +
                    lcgdppc + 
                    cabinet_size + 
                    left_truncated'


events_senior <- '+ ln_oilgas_rents + 
                  pers_2pl +
                  leader_exit + 
                  leader_tenure +
                  I(leader_tenure^2) +
                  I(leader_tenure^3) +
                  election_corrected + 
                  coup_corrected + 
                  lcgdppc + 
                  cabinet_size + 
                  left_truncated'


aid_dem_senior <- '+ ln_oilgas_rents +
                  ln_total_aid_AD +
                  v2x_polyarchy +
                  pers_2pl +
                  leader_exit + 
                  leader_tenure +
                  I(leader_tenure^2) +
                  I(leader_tenure^3) +
                  election_corrected + 
                  coup_corrected + 
                  lcgdppc + 
                  cabinet_size + 
                  left_truncated'

model_specs_senior <- list(none, baseline, tenure_senior, 
                           events_senior, aid_dem_senior)

Figure_A1<- lapply(cwe_options, function(x){
  
  lapply(model_specs_senior, function(controls){
    model <-  glm(as.formula(paste('spell_end ~', 
                                   x, controls)), 
                  data = gwf_ssa_senior, 
                  family = binomial)
    
    clustered_vcov <- cluster.vcov(model, gwf_ssa_senior$leaderID)
    
    #marginal effects 
    data.frame(summary(margins(model, vcov = clustered_vcov))) %>%
      mutate(model = 'Pooled', 
             sample = 'Senior Ministers') %>%
      filter(grepl('CWE', factor)==T)
  })
})


senior_margins_df <- bind_rows(Figure_A1) %>%
  mutate(specification = rep(c('No Controls', 
                               '+ Baseline',
                               '+ Tenure',
                               '+ Events',
                               '+ Extras'), 5), 
         specification = factor(specification, 
                                levels = c('No Controls', 
                                           '+ Baseline',
                                           '+ Tenure',
                                           '+ Events',
                                           '+ Extras'))) %>%
  filter(specification != '+ Extras') %>%
  mutate(window_size = case_when(factor=='CWE_5' ~ 1, 
                                 factor=='CWE_4' ~ 2, 
                                 factor=='CWE_3' ~ 3, 
                                 factor=='CWE_2' ~ 4, 
                                 factor=='CWE_1' ~ 5))


ggplot(senior_margins_df, aes(y = AME, x = window_size, 
                              color = specification, ymin = lower, ymax = upper)) +
  geom_pointrange(position = position_dodge(width = .4)) +
  scale_color_manual(values = c('gray10',
                                'gray30',
                                'gray50',
                                'gray70')) +
  scale_x_continuous(breaks = c(seq(1, 5, 1)), 
                     labels = c(seq(5, 1, -1))) +
  scale_y_continuous(breaks = c(seq(0, .4, .1)), 
                     labels = c(seq(0, .4, .1)), 
                     limits = c(-.01, .45)) +
  labs(y = 'Average Marginal Effect of CWE', x = 'Window Size (Years)', 
       color = '') +
  theme_pubclean() +
  theme(panel.background = element_rect(fill = 'white'),
        legend.key = element_rect(fill = 'white'),
        axis.ticks.x = element_blank()) 

ggsave('Fig2_Senior_AMEs.pdf', 
       width = 6, height = 4)




#Pooled logit models across CWE windows on GWF SSA senior minister only sample
pooled_logit_senior_only <- function(xvar){
  
  lapply(model_specs_senior, function(controls){
    
    model <- glm(as.formula(paste('spell_end ~', 
                                  xvar, controls)), 
                 data = gwf_ssa_senior, 
                 family = binomial)
    
    
    SEs <- sqrt(diag(cluster.vcov(model, gwf_ssa_senior$leaderID)))
    
    return(list(model, SEs))
    
  })
}


#5year window, all control sets

A32 <- pooled_logit_senior_only('CWE_5')

#table of results
stargazer(A32[[1]][[1]], A32[[2]][[1]], 
          A32[[3]][[1]], A32[[4]][[1]], 
          A32[[5]][[1]], 
          se = list(A32[[1]][[2]], A32[[2]][[2]], 
                    A32[[3]][[2]], A32[[4]][[2]], 
                    A32[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 5-year', 
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_senior_pooled.tex')


#4 year window, all control sets

A33 <- pooled_logit_senior_only('CWE_4')


#table of results
stargazer(A33[[1]][[1]], A33[[2]][[1]], 
          A33[[3]][[1]], A33[[4]][[1]], 
          A33[[5]][[1]], 
          se = list(A33[[1]][[2]], A33[[2]][[2]], 
                    A33[[3]][[2]], A33[[4]][[2]], 
                    A33[[5]][[2]]), 
          table.placement = '!hbt',
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 4-year', 
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          title = 'Pooled Logit of Minister Survival with 4-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe4_senior_pooled.tex')

#3 year window, all control sets

A34 <- pooled_logit_senior_only('CWE_3')

#table of results
stargazer(A34[[1]][[1]], A34[[2]][[1]], 
          A34[[3]][[1]], A34[[4]][[1]], 
          A34[[5]][[1]], 
          se = list(A34[[1]][[2]], A34[[2]][[2]], 
                    A34[[3]][[2]], A34[[4]][[2]], 
                    A34[[5]][[2]]),
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 3-year', 
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 3-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe3_senior_pooled.tex')

#2 year window, all control set

A35 <- pooled_logit_senior_only('CWE_2')

stargazer(A35[[1]][[1]], A35[[2]][[1]], 
          A35[[3]][[1]], A35[[4]][[1]], 
          A35[[5]][[1]], 
          se = list(A35[[1]][[2]], A35[[2]][[2]], 
                    A35[[3]][[2]], A35[[4]][[2]], 
                    A35[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 2-year', 
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 2-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe2_senior_pooled.tex')

#1 year window, all control sets

A36 <- pooled_logit_senior_only('CWE_1')

#table of results
stargazer(A36[[1]][[1]], A36[[2]][[1]], 
          A36[[3]][[1]], A36[[4]][[1]], 
          A36[[5]][[1]], 
          se = list(A36[[1]][[2]], A36[[2]][[2]], 
                    A36[[3]][[2]], A36[[4]][[2]], 
                    A36[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 1-year', 
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 1-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe1_senior_pooled.tex')


#A4.3 FE Models on Senior Minister Only Sample


fe_logit_senior <- function(xvar){
  
  lapply(model_specs_all, function(controls){
    
    clogit(as.formula(paste0('spell_end ~', xvar, paste0(controls),
                             '+ strata(leaderID)')), 
           data = gwf_ssa_senior, 
           method = 'efron',
           cluster = leaderID)
  })
}


#5 year window

A37 <- fe_logit_senior('CWE_5')

A37_results <- lapply(A37, broom::tidy)

stargazer(A37[[1]], 
          A37[[2]], 
          A37[[3]], 
          A37[[4]], 
          A37[[5]], 
          coef = list(A37_results[[1]]$estimate, 
                      A37_results[[2]]$estimate, 
                      A37_results[[3]]$estimate, 
                      A37_results[[4]]$estimate, 
                      A37_results[[5]]$estimate), 
          se = list(A37_results[[1]]$robust.se, 
                    A37_results[[2]]$robust.se, 
                    A37_results[[3]]$robust.se, 
                    A37_results[[4]]$robust.se, 
                    A37_results[[5]]$robust.se), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 
                               'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size',
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects', 'Yes', 'Yes', 'Yes',
                             'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_senior_fe.tex')


#4 year window

A38 <- fe_logit_senior('CWE_4')

A38_results <- lapply(A38, broom::tidy)

stargazer(A38[[1]], 
          A38[[2]], 
          A38[[3]], 
          A38[[4]], 
          A38[[5]], 
          coef = list(A38_results[[1]]$estimate, 
                      A38_results[[2]]$estimate, 
                      A38_results[[3]]$estimate, 
                      A38_results[[4]]$estimate, 
                      A38_results[[5]]$estimate), 
          se = list(A38_results[[1]]$robust.se, 
                    A38_results[[2]]$robust.se, 
                    A38_results[[3]]$robust.se, 
                    A38_results[[4]]$robust.se, 
                    A38_results[[5]]$robust.se), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 4-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 
                               'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size',
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects', 'Yes', 'Yes', 'Yes',
                             'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 4-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe4_senior_fe.tex')



#3 year window

A39 <- fe_logit_senior('CWE_3')

A39_results <- lapply(A39, broom::tidy)

stargazer(A39[[1]], 
          A39[[2]], 
          A39[[3]], 
          A39[[4]], 
          A39[[5]], 
          coef = list(A39_results[[1]]$estimate, 
                      A39_results[[2]]$estimate, 
                      A39_results[[3]]$estimate, 
                      A39_results[[4]]$estimate, 
                      A39_results[[5]]$estimate), 
          se = list(A39_results[[1]]$robust.se, 
                    A39_results[[2]]$robust.se, 
                    A39_results[[3]]$robust.se, 
                    A39_results[[4]]$robust.se, 
                    A39_results[[5]]$robust.se), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 3-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 
                               'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size',
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects', 'Yes', 'Yes', 'Yes',
                             'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 3-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe3_senior_fe.tex')



#2 year window

A40 <- fe_logit_senior('CWE_2')

A40_results <- lapply(A40, broom::tidy)

stargazer(A40[[1]], 
          A40[[2]], 
          A40[[3]], 
          A40[[4]], 
          A40[[5]], 
          coef = list(A40_results[[1]]$estimate, 
                      A40_results[[2]]$estimate, 
                      A40_results[[3]]$estimate, 
                      A40_results[[4]]$estimate, 
                      A40_results[[5]]$estimate), 
          se = list(A40_results[[1]]$robust.se, 
                    A40_results[[2]]$robust.se, 
                    A40_results[[3]]$robust.se, 
                    A40_results[[4]]$robust.se, 
                    A40_results[[5]]$robust.se), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 2-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 
                               'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size',
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects', 'Yes', 'Yes', 'Yes',
                             'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 2-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe2_senior_fe.tex')



#1 year window

A41 <- fe_logit_senior('CWE_1')

A41_results <- lapply(A41, broom::tidy)

stargazer(A41[[1]], 
          A41[[2]], 
          A41[[3]], 
          A41[[4]], 
          A41[[5]], 
          coef = list(A41_results[[1]]$estimate, 
                      A41_results[[2]]$estimate, 
                      A41_results[[3]]$estimate, 
                      A41_results[[4]]$estimate, 
                      A41_results[[5]]$estimate), 
          se = list(A41_results[[1]]$robust.se, 
                    A41_results[[2]]$robust.se, 
                    A41_results[[3]]$robust.se, 
                    A41_results[[4]]$robust.se, 
                    A41_results[[5]]$robust.se), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 1-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 
                               'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size',
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects', 'Yes', 'Yes', 'Yes',
                             'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 1-year CWE Window, Senior Minister Only GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe1_senior_fe.tex')



# Section A5 --------------------------------------------------------------


gwf_ssa_coercive <- gwf_ssa %>%
  filter(survival_portfolio==1)



pooled_logit_coercive <- function(xvar){
  
  lapply(model_specs_all, function(controls){
    
    model <- glm(as.formula(paste('spell_end ~', 
                                  xvar, controls)), 
                 data = gwf_ssa_coercive, 
                 family = binomial)
    
    
    SEs <- sqrt(diag(cluster.vcov(model, gwf_ssa_coercive$leaderID)))
    
    return(list(model, SEs))
    
  })
}


#5year window, all control sets

A43 <- pooled_logit_coercive('CWE_5')

#table of results
stargazer(A43[[1]][[1]], A43[[2]][[1]], 
          A43[[3]][[1]], A43[[4]][[1]], 
          A43[[5]][[1]], 
          se = list(A43[[1]][[2]], A43[[2]][[2]], 
                    A43[[3]][[2]], A43[[4]][[2]], 
                    A43[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, GWF SSA Sample Limited to Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe5_coercive_pooled',
          out = 'cwe5_coercive_pooled.tex')


#4 year window, all control sets

A44 <- pooled_logit_coercive('CWE_4')


#table of results
stargazer(A44[[1]][[1]], A44[[2]][[1]], 
          A44[[3]][[1]], A44[[4]][[1]], 
          A44[[5]][[1]], 
          se = list(A44[[1]][[2]], A44[[2]][[2]], 
                    A44[[3]][[2]], A44[[4]][[2]], 
                    A44[[5]][[2]]), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 4-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 4-year CWE Window, GWF SSA Sample Limited to Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe4_coercive_pooled',
          out = 'cwe4_coercive_pooled.tex')

#3 year window, all control sets

A45 <- pooled_logit_coercive('CWE_3')

#table of results
stargazer(A45[[1]][[1]], A45[[2]][[1]], 
          A45[[3]][[1]], A45[[4]][[1]], 
          A45[[5]][[1]], 
          se = list(A45[[1]][[2]], A45[[2]][[2]], 
                    A45[[3]][[2]], A45[[4]][[2]], 
                    A45[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 3-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 3-year CWE Window, GWF SSA Sample Limited to Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe3_coercive_pooled',
          out = 'cwe3_coercive_pooled.tex')

#2 year window, all control set

A46 <- pooled_logit_coercive('CWE_2')

stargazer(A46[[1]][[1]], A46[[2]][[1]], 
          A46[[3]][[1]], A46[[4]][[1]], 
          A46[[5]][[1]], 
          se = list(A46[[1]][[2]], A46[[2]][[2]], 
                    A46[[3]][[2]], A46[[4]][[2]], 
                    A46[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 2-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 2-year CWE Window, GWF SSA Sample Limited to Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe2_coercive_pooled',
          out = 'cwe2_coercive_pooled.tex')

#1 year window, all control sets

A47 <- pooled_logit_coercive('CWE_1')

#table of results
stargazer(A47[[1]][[1]], A47[[2]][[1]], 
          A47[[3]][[1]], A47[[4]][[1]], 
          A47[[5]][[1]], 
          se = list(A47[[1]][[2]], A47[[2]][[2]], 
                    A47[[3]][[2]], A47[[4]][[2]], 
                    A47[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 1-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 1-year CWE Window, GWF SSA Sample Limited to Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe1_coercive_pooled',
          out = 'cwe1_coercive_pooled.tex')


#Figure A2 marginal effects and plot for coercive portfolios

Figure_A2 <- lapply(cwe_options, function(x){
  
  lapply(model_specs, function(controls){
    model <-  glm(as.formula(paste('spell_end ~', 
                                   x, controls)), 
                  data = gwf_ssa_coercive, 
                  family = binomial)
    
    clustered_vcov <- cluster.vcov(model, gwf_ssa_coercive$leaderID)
    
    #marginal effects 
    data.frame(summary(margins(model, vcov = clustered_vcov))) %>%
      mutate(model = 'Pooled', 
             sample = 'Coercive Portfolio') %>%
      filter(grepl('CWE', factor)==T)
  })
})


high_margins_df <- bind_rows(Figure_A2) %>%
  mutate(specification = rep(c('No Controls', 
                               '+ Baseline',
                               '+ Tenure',
                               '+ Events'), 5), 
         specification = factor(specification, 
                                levels = c('No Controls', 
                                           '+ Baseline',
                                           '+ Tenure',
                                           '+ Events'))) %>%
  filter(specification != '+ Extras') %>%
  mutate(window_size = case_when(factor=='CWE_5' ~ 1, 
                                 factor=='CWE_4' ~ 2, 
                                 factor=='CWE_3' ~ 3, 
                                 factor=='CWE_2' ~ 4, 
                                 factor=='CWE_1' ~ 5))


ggplot(high_margins_df, aes(y = AME, x = window_size, 
                            color = specification, ymin = lower, ymax = upper)) +
  geom_pointrange(position = position_dodge(width = .4)) +
  scale_color_manual(values = c('gray10',
                                'gray30',
                                'gray50',
                                'gray70')) +
  scale_x_continuous(breaks = c(seq(1, 5, 1)), 
                     labels = c(seq(5, 1, -1))) +
  scale_y_continuous(breaks = c(seq(0, .4, .1)), 
                     labels = c(seq(0, .4, .1)), 
                     limits = c(-.01, .41)) +
  labs(y = 'Average Marginal Effect of CWE', x = 'Window Size (Years)', 
       color = '') +
  theme_pubclean() +
  theme(panel.background = element_rect(fill = 'white'),
        legend.key = element_rect(fill = 'white'),
        axis.ticks.x = element_blank()) 

ggsave('Fig2_Coercive_Portfolio_AMEs.pdf', 
       width = 6, height = 4)


#A5.3 Conditional logit (leader fixed effects) models of minister survival,
#coercive portfolio minister only sample

fe_logit_coercive <- function(xvar){
  
  lapply(model_specs_all, function(controls){
    
    clogit(as.formula(paste0('spell_end ~', xvar, paste0(controls),
                             '+ strata(leaderID)')), 
           data = gwf_ssa_coercive, 
           method = 'efron',
           cluster = leaderID)
  })
}


#5 year window

A48<- fe_logit_coercive('CWE_5')

A48_results <- lapply(A48, broom::tidy)

stargazer(A48[[1]], 
          A48[[2]], 
          A48[[3]], 
          A48[[4]], 
          A48[[5]], 
          coef = list(A48_results[[1]]$estimate, 
                      A48_results[[2]]$estimate, 
                      A48_results[[3]]$estimate, 
                      A48_results[[4]]$estimate, 
                      A48_results[[5]]$estimate), 
          se = list(A48_results[[1]]$robust.se, 
                    A48_results[[2]]$robust.se, 
                    A48_results[[3]]$robust.se, 
                    A48_results[[4]]$robust.se, 
                    A48_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Only Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe5_coercive_fe',
          out = 'cwe5_coercive_fe.tex')

#4 year window

A49 <- fe_logit_coercive("CWE_4")

A49_results <- lapply(A49, broom::tidy)

stargazer(A49[[1]], 
          A49[[2]], 
          A49[[3]], 
          A49[[4]], 
          A49[[5]], 
          coef = list(A49_results[[1]]$estimate, 
                      A49_results[[2]]$estimate, 
                      A49_results[[3]]$estimate, 
                      A49_results[[4]]$estimate, 
                      A49_results[[5]]$estimate), 
          se = list(A49_results[[1]]$robust.se, 
                    A49_results[[2]]$robust.se, 
                    A49_results[[3]]$robust.se, 
                    A49_results[[4]]$robust.se, 
                    A49_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 4-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 4-year CWE Window, Only Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe4_coercive_fe',
          out = 'cwe4_coercive_fe.tex')


#3 year window

A50 <- fe_logit_coercive("CWE_3")

A50_results <- lapply(A50, broom::tidy)

stargazer(A50[[1]], 
          A50[[2]], 
          A50[[3]], 
          A50[[4]], 
          A50[[5]], 
          coef = list(A50_results[[1]]$estimate, 
                      A50_results[[2]]$estimate, 
                      A50_results[[3]]$estimate, 
                      A50_results[[4]]$estimate, 
                      A50_results[[5]]$estimate), 
          se = list(A50_results[[1]]$robust.se, 
                    A50_results[[2]]$robust.se, 
                    A50_results[[3]]$robust.se, 
                    A50_results[[4]]$robust.se, 
                    A50_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 3-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 3-year CWE Window, Only Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe3_coercive_fe',
          out = 'cwe3_coercive_fe.tex')


#2 year window

A51 <- fe_logit_coercive("CWE_2")

A51_results <- lapply(A51, broom::tidy)

stargazer(A51[[1]], 
          A51[[2]], 
          A51[[3]], 
          A51[[4]], 
          A51[[5]], 
          coef = list(A51_results[[1]]$estimate, 
                      A51_results[[2]]$estimate, 
                      A51_results[[3]]$estimate, 
                      A51_results[[4]]$estimate, 
                      A51_results[[5]]$estimate), 
          se = list(A51_results[[1]]$robust.se, 
                    A51_results[[2]]$robust.se, 
                    A51_results[[3]]$robust.se, 
                    A51_results[[4]]$robust.se, 
                    A51_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 2-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 2-year CWE Window, Only Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe2_coercive_fe',
          out = 'cwe2_coercive_fe.tex')

#1 year window

A52 <- fe_logit_coercive("CWE_1")

A52_results <- lapply(A52, broom::tidy)

stargazer(A52[[1]], 
          A52[[2]], 
          A52[[3]], 
          A52[[4]], 
          A52[[5]], 
          coef = list(A52_results[[1]]$estimate, 
                      A52_results[[2]]$estimate, 
                      A52_results[[3]]$estimate, 
                      A52_results[[4]]$estimate, 
                      A52_results[[5]]$estimate), 
          se = list(A52_results[[1]]$robust.se, 
                    A52_results[[2]]$robust.se, 
                    A52_results[[3]]$robust.se, 
                    A52_results[[4]]$robust.se, 
                    A52_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 1-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 1-year CWE Window, Only Coercive Portfolio Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          label = 'tab:cwe1_coercive_fe',
          out = 'cwe1_coercive_fe.tex')


# Section A6 --------------------------------------------------------------
#High prestige minister exit analyses


#zelig logit function
zelig_pooled_high_logit <- function(xvar){
  
  zelig(as.formula(paste0('spell_end ~', xvar,"*",'high_prestige', 
                          '+ minister_tenure +
                          I(minister_tenure^2) +
                          I(minister_tenure^3) +
                   ln_oilgas_rents +
                   pers_2pl +
                   leader_exit + 
                   leader_tenure +
                   I(leader_tenure^2) +
                   I(leader_tenure^3) +
                   election_corrected + 
                   coup_corrected + 
                   lcgdppc + 
                   cabinet_size + 
                   left_truncated')),
        data = gwf_ssa, 
        model = 'logit', 
        cite = F)
}

#5 year window, high prestige
z.5year_high <- zelig_pooled_high_logit('CWE_5')
summary(z.5year_high)

#4 year window
z.4year_high <- zelig_pooled_high_logit("CWE_4")

#3 year window
z.3year_high <- zelig_pooled_high_logit('CWE_3')

#2 year window
z.2year_high <- zelig_pooled_high_logit('CWE_2')

#1 year window
z.1year_high <- zelig_pooled_high_logit('CWE_1')
summary(z.1year_high)

#High prestige/non-high prestige simulations

#non-high prestige ministers 5 year window
x.5.noncwe_nh <- setx(z.5year_high, CWE_5 = 0, high_prestige = 0)
x.5.cwe_nh <- setx(z.5year_high, CWE_5 = 1, high_prestige = 0)
s.5.out_nh <- sim(z.5year_high, x = x.5.noncwe_nh, x1 = x.5.cwe_nh)



#non-high prestige ministers 4 year window
x.4.noncwe_nh <- setx(z.4year_high, CWE_4 = 0, high_prestige = 0)
x.4.cwe_nh <- setx(z.4year_high, CWE_4 = 1, high_prestige = 0)
s.4.out_nh <- sim(z.4year_high, x = x.4.noncwe_nh, x1 = x.4.cwe_nh)
summary(s.4.out_nh)

#non-high prestige ministers 3 year window
x.3.noncwe_nh <- setx(z.3year_high, CWE_3 = 0, high_prestige = 0)
x.3.cwe_nh <- setx(z.3year_high, CWE_3 = 1, high_prestige = 0)
s.3.out_nh <- sim(z.3year_high, x = x.3.noncwe_nh, x1 = x.3.cwe_nh)
summary(s.3.out_nh)



#non-high prestige ministers 2 year window
x.2.noncwe_nh <- setx(z.2year_high, CWE_2 = 0, high_prestige = 0)
x.2.cwe_nh <- setx(z.2year_high, CWE_2 = 1, high_prestige = 0)
s.2.out_nh <- sim(z.2year_high, x = x.2.noncwe_nh, x1 = x.2.cwe_nh)
summary(s.2.out_nh)



#non-high prestige ministers 1 year window
x.1.noncwe_nh <- setx(z.1year_high, CWE_1 = 0, high_prestige = 0)
x.1.cwe_nh <- setx(z.1year_high, CWE_1 = 1, high_prestige = 0)
s.1.out_nh <- sim(z.1year_high, x = x.1.noncwe_nh, x1 = x.1.cwe_nh)
summary(s.1.out_nh)

#high prestige ministers 5 year window
x.5.noncwe_h <- setx(z.5year_high, CWE_5 = 0, high_prestige = 1)
x.5.cwe_h <- setx(z.5year_high, CWE_5 = 1, high_prestige = 1)
s.5.out_h <- sim(z.5year_high, x = x.5.noncwe_h, x1 = x.5.cwe_h)
summary(s.5.out_h)

#high prestige ministers 4 year window
x.4.noncwe_h <- setx(z.4year_high, CWE_4 = 0, high_prestige  = 1)
x.4.cwe_h <- setx(z.4year_high, CWE_4 = 1, high_prestige  = 1)
s.4.out_h <- sim(z.4year_high, x = x.4.noncwe_h, x1 = x.4.cwe_h)
summary(s.4.out_h)


#high prestige ministers 3 year window
x.3.noncwe_h <- setx(z.3year_high, CWE_3 = 0, high_prestige = 1)
x.3.cwe_h <- setx(z.3year_high, CWE_3 = 1, high_prestige = 1)
s.3.out_h <- sim(z.3year_high, x = x.3.noncwe_h, x1 = x.3.cwe_h)
summary(s.3.out_h)


#high prestige ministers 2 year window
x.2.noncwe_h <- setx(z.2year_high, CWE_2 = 0,high_prestige = 1)
x.2.cwe_h <- setx(z.2year_high, CWE_2 = 1, high_prestige = 1)
s.2.out_h <- sim(z.2year_high, x = x.2.noncwe_h, x1 = x.2.cwe_h)
summary(s.2.out_h)




#senior ministers 1 year window
x.1.noncwe_h <- setx(z.1year_high, CWE_1 = 0, high_prestige = 1)
x.1.cwe_h <- setx(z.1year_high, CWE_1 = 1, high_prestige = 1)
s.1.out_h <- sim(z.1year_high, x = x.1.noncwe_h, x1 = x.1.cwe_h)

#extract all simulation results to dataframe

all_sims_high <- list(s.5.out_nh, s.4.out_nh, 
                      s.3.out_nh, s.2.out_nh,
                      s.1.out_nh, s.5.out_h,
                      s.4.out_h, s.3.out_h, 
                      s.2.out_h, s.1.out_h)

all_sims_results_high <- lapply(all_sims_high, zelig_results) %>%
  bind_rows(.) %>%
  mutate(minister = c(rep("Low/Medium", 5), rep("High", 5)),
         minister = factor(minister, levels = c("Low/Medium",
                                                "High")),
         window_size = c(rep(seq(5,1,-1), 2)), 
         window_size = factor(window_size, levels = c(5, 4, 3, 2, 1))) 


#Figure A3: Difference in minister exit probabilities at CWE=1 and
#CWE=0 for ministers in high prestige and medium/low presige portfolios

ggplot(all_sims_results_high, aes(x = window_size, y = fd, ymin = ll, ymax = ul)) +
  geom_pointrange() +
  facet_wrap(~minister) +
  scale_y_continuous(breaks = c(seq(0, .6, .1)),
                     limits = c(0, .61)) +
  labs(x = 'Window Size (Years)', y = 'First Difference') +
  theme_pubclean()

ggsave('LowMed_High_Diff.pdf', 
       width = 6, height = 4)


high_pooled_logit <- function(xvar){
  
  high_df <- gwf_ssa %>%
    mutate(cwe_option = !!sym(xvar))
  
  glm(spell_end ~ cwe_option*high_prestige + 
        ln_oilgas_rents +
        pers_2pl +
        leader_exit + 
        leader_tenure +
        I(leader_tenure^2) +
        I(leader_tenure^3) +
        election_corrected + 
        coup_corrected + 
        lcgdppc + 
        cabinet_size + 
        left_truncated,
      data = high_df, 
      family = binomial)
}

A53 <- lapply(cwe_options, high_pooled_logit)


#table of results
stargazer(A53[[1]], A53[[2]],
          A53[[3]], A53[[4]],
          A53[[5]], 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('CWE 5-year', 'CWE 4-year', 
                             'CWE 3-year', 'CWE 2-year',
                             'CWE 1-year'), 
          order = c(1, 2, 14, 3, 4, 5, 6, 7, 
                    8, 9, 10, 11, 12, 13),
          digits = 2,
          covariate.labels = c('CWE Window', 
                               'High Prestige',
                               'CWE X High Prestige',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 
                               'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit Models with High Prestige by CWE Interaction', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe_high_pooled.tex')



gwf_ssa_high <- gwf_ssa %>%
  filter(high_prestige==1)

#model function
pooled_logit_high <- function(xvar){
  
  lapply(model_specs_all, function(controls){
    
    model <- glm(as.formula(paste('spell_end ~', 
                                  xvar, controls)), 
                 data = gwf_ssa_high, 
                 family = binomial)
    
    
    SEs <- sqrt(diag(cluster.vcov(model, gwf_ssa_high$leaderID)))
    
    return(list(model, SEs))
    
  })
}


#5year window, all control sets

A54 <- pooled_logit_high('CWE_5')

#table of results
stargazer(A54[[1]][[1]], A54[[2]][[1]], 
          A54[[3]][[1]], A54[[4]][[1]], 
          A54[[5]][[1]], 
          se = list(A54[[1]][[2]], A54[[2]][[2]], 
                    A54[[3]][[2]], A54[[4]][[2]], 
                    A54[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 5-year CWE Window, GWF SSA Sample Limited to High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_high_pooled.tex')


#4 year window, all control sets

A55 <- pooled_logit_high('CWE_4')


#table of results
stargazer(A55[[1]][[1]], A55[[2]][[1]], 
          A55[[3]][[1]], A55[[4]][[1]], 
          A55[[5]][[1]], 
          se = list(A55[[1]][[2]], A55[[2]][[2]], 
                    A55[[3]][[2]], A55[[4]][[2]], 
                    A55[[5]][[2]]), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 4-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 4-year CWE Window, GWF SSA Sample Limited to High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe4_high_pooled.tex')

#3 year window, all control sets

A56 <- pooled_logit_high('CWE_3')

#table of results
stargazer(A56[[1]][[1]], A56[[2]][[1]], 
          A56[[3]][[1]], A56[[4]][[1]], 
          A56[[5]][[1]], 
          se = list(A56[[1]][[2]], A56[[2]][[2]], 
                    A56[[3]][[2]], A56[[4]][[2]], 
                    A56[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 3-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 3-year CWE Window, GWF SSA Sample Limited to High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe3_high_pooled.tex')

#2 year window, all control set

A57 <- pooled_logit_high('CWE_2')

stargazer(A57[[1]][[1]], A57[[2]][[1]], 
          A57[[3]][[1]], A57[[4]][[1]], 
          A57[[5]][[1]], 
          se = list(A57[[1]][[2]], A57[[2]][[2]], 
                    A57[[3]][[2]], A57[[4]][[2]], 
                    A57[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 2-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 2-year CWE Window, GWF SSA Sample Limited to High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe2_high_pooled.tex')

#1 year window, all control sets

A58 <- pooled_logit_high('CWE_1')

#table of results
stargazer(A58[[1]][[1]], A58[[2]][[1]], 
          A58[[3]][[1]], A58[[4]][[1]], 
          A58[[5]][[1]], 
          se = list(A58[[1]][[2]], A58[[2]][[2]], 
                    A58[[3]][[2]], A58[[4]][[2]], 
                    A58[[5]][[2]]), 
          table.placement = '!hbt',
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 1-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Ln(Total Aid)',
                               'VDem Polyarchy',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 
                               'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit of Minister Survival with 1-year CWE Window, GWF SSA Sample Limited to High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          no.space = T,
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe1_high_pooled.tex')


#marginal effects and plot for high prestige models


Figure_A4 <- lapply(cwe_options, function(x){
  
  lapply(model_specs, function(controls){
    model <-  glm(as.formula(paste('spell_end ~', 
                                   x, controls)), 
                  data = gwf_ssa_high, 
                  family = binomial)
    
    clustered_vcov <- cluster.vcov(model, gwf_ssa_high$leaderID)
    
    #marginal effects 
    data.frame(summary(margins(model, vcov = clustered_vcov))) %>%
      mutate(model = 'Pooled', 
             sample = 'High Prestige') %>%
      filter(grepl('CWE', factor)==T)
  })
})


high_margins_df <- bind_rows(Figure_A4) %>%
  mutate(specification = rep(c('No Controls', 
                               '+ Baseline',
                               '+ Tenure',
                               '+ Events'), 5), 
         specification = factor(specification, 
                                levels = c('No Controls', 
                                           '+ Baseline',
                                           '+ Tenure',
                                           '+ Events'))) %>%
  filter(specification != '+ Extras') %>%
  mutate(window_size = case_when(factor=='CWE_5' ~ 1, 
                                 factor=='CWE_4' ~ 2, 
                                 factor=='CWE_3' ~ 3, 
                                 factor=='CWE_2' ~ 4, 
                                 factor=='CWE_1' ~ 5))

#Figure A4: Average marginal effect of CWE window variables,
#High prestige minister only sample

ggplot(high_margins_df, aes(y = AME, x = window_size, 
                            color = specification, ymin = lower, ymax = upper)) +
  geom_pointrange(position = position_dodge(width = .4)) +
  scale_color_manual(values = c('gray10',
                                'gray30',
                                'gray50',
                                'gray70')) +
  scale_x_continuous(breaks = c(seq(1, 5, 1)), 
                     labels = c(seq(5, 1, -1))) +
  scale_y_continuous(breaks = c(seq(0, .4, .1)), 
                     labels = c(seq(0, .4, .1)), 
                     limits = c(-.01, .41)) +
  labs(y = 'Average Marginal Effect of CWE', x = 'Window Size (Years)', 
       color = '') +
  theme_pubclean() +
  theme(panel.background = element_rect(fill = 'white'),
        legend.key = element_rect(fill = 'white'),
        axis.ticks.x = element_blank()) 

ggsave('Fig2_High_Prestige_AMEs.pdf', 
       width = 6, height = 4)



fe_logit_high <- function(xvar){
  
  lapply(model_specs_all, function(controls){
    
    clogit(as.formula(paste0('spell_end ~', xvar, paste0(controls),
                             '+ strata(leaderID)')), 
           data = gwf_ssa_high, 
           method = 'efron',
           cluster = leaderID)
  })
}


#5 year window

A59 <- fe_logit_high('CWE_5')

A59_results <- lapply(A59, broom::tidy)

stargazer(A59[[1]], 
          A59[[2]], 
          A59[[3]], 
          A59[[4]], 
          A59[[5]], 
          coef = list(A59_results[[1]]$estimate, 
                      A59_results[[2]]$estimate, 
                      A59_results[[3]]$estimate, 
                      A59_results[[4]]$estimate, 
                      A59_results[[5]]$estimate), 
          se = list(A59_results[[1]]$robust.se, 
                    A59_results[[2]]$robust.se, 
                    A59_results[[3]]$robust.se, 
                    A59_results[[4]]$robust.se, 
                    A59_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 5-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 5-year CWE Window, Only High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_high_fe.tex')

#4 year window

A60 <- fe_logit_high("CWE_4")

A60_results <- lapply(A60, broom::tidy)

stargazer(A60[[1]], 
          A60[[2]], 
          A60[[3]], 
          A60[[4]], 
          A60[[5]], 
          coef = list(A60_results[[1]]$estimate, 
                      A60_results[[2]]$estimate, 
                      A60_results[[3]]$estimate, 
                      A60_results[[4]]$estimate, 
                      A60_results[[5]]$estimate), 
          se = list(A60_results[[1]]$robust.se, 
                    A60_results[[2]]$robust.se, 
                    A60_results[[3]]$robust.se, 
                    A60_results[[4]]$robust.se, 
                    A60_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 4-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 4-year CWE Window, Only High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe4_high_fe.tex')


#3 year window

A61 <- fe_logit_high("CWE_3")

A61_results <- lapply(A61, broom::tidy)

stargazer(A61[[1]], 
          A61[[2]], 
          A61[[3]], 
          A61[[4]], 
          A61[[5]], 
          coef = list(A61_results[[1]]$estimate, 
                      A61_results[[2]]$estimate, 
                      A61_results[[3]]$estimate, 
                      A61_results[[4]]$estimate, 
                      A61_results[[5]]$estimate), 
          se = list(A61_results[[1]]$robust.se, 
                    A61_results[[2]]$robust.se, 
                    A61_results[[3]]$robust.se, 
                    A61_results[[4]]$robust.se, 
                    A61_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 3-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 3-year CWE Window, Only High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe3_high_fe.tex')


#2 year window

A62 <- fe_logit_high("CWE_2")

A62_results <- lapply(A62, broom::tidy)

stargazer(A62[[1]], 
          A62[[2]], 
          A62[[3]], 
          A62[[4]], 
          A62[[5]], 
          coef = list(A62_results[[1]]$estimate, 
                      A62_results[[2]]$estimate, 
                      A62_results[[3]]$estimate, 
                      A62_results[[4]]$estimate, 
                      A62_results[[5]]$estimate), 
          se = list(A62_results[[1]]$robust.se, 
                    A62_results[[2]]$robust.se, 
                    A62_results[[3]]$robust.se, 
                    A62_results[[4]]$robust.se, 
                    A62_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 2-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 2-year CWE Window, Only High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe2_high_fe.tex')

#1 year window

A63 <- fe_logit_high("CWE_1")

A63_results <- lapply(A63, broom::tidy)

stargazer(A63[[1]], 
          A63[[2]], 
          A63[[3]], 
          A63[[4]], 
          A63[[5]], 
          coef = list(A63_results[[1]]$estimate, 
                      A63_results[[2]]$estimate, 
                      A63_results[[3]]$estimate, 
                      A63_results[[4]]$estimate, 
                      A63_results[[5]]$estimate), 
          se = list(A63_results[[1]]$robust.se, 
                    A63_results[[2]]$robust.se, 
                    A63_results[[3]]$robust.se, 
                    A63_results[[4]]$robust.se, 
                    A63_results[[5]]$robust.se), 
          table.placement = '!hbt',
          
          dep.var.labels = 'Minister Exit',
          column.labels  = c('No Controls', 'Baseline', 
                             'Tenure', 'Events', 'Extras'), 
          covariate.labels = c('CWE 1-year', 'Minister Tenure',
                               'Minister Tenure$^{2}$', 
                               'Minister Tenure$^{3}$',
                               'Ln(Oil/Gas Rents)',
                               'Personalism', 'Leader Exit',
                               'Leader Tenure',
                               'Leader Tenure$^{2}$', 
                               'Leader Tenure$^{3}$',
                               'Election',
                               'Failed Coup',
                               'Ln(GDP per Capita)', 
                               'Cabinet Size', 'Left Truncated'),
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          digits = 2,
          no.space = T,
          add.lines = list(c('Leader Fixed Effects?', 'Yes', 'Yes', 
                             'Yes', 'Yes', 'Yes')),
          title = 'Conditional Logit of Minister Survival with 1-year CWE Window, Only High Prestige Ministers', 
          notes = 'Standard errors clustered by leader.', 
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe1_high_fe.tex')


# Section A7 --------------------------------------------------------------
#Yearly leader and minister turnover

#Yearly percent of leaders exiting across all countries in gwf_ssa sample
leader_turnover <- cy %>%
  filter(!is.na(gwf_regimetype)) %>%
  filter(!(country_name %in% nafrica_sa)) %>%
  arrange(year, leaderID, leader_name) %>%
  group_by(year) %>%
  summarise(leaders = n(), 
            leader_exits = sum(leader_exit)) %>%
  mutate(exit_percent = 100*(leader_exits/leaders), 
         type = 'Leader') %>%
  dplyr::select(year, exit_percent, type)

#Yearly percent of ministers exiting across all countries in gwf_ssa sample
minister_turnover <- df %>%
  filter(!is.na(gwf_regimetype)) %>%
  filter(!(country_name %in% nafrica_sa)) %>%
  arrange(cowcode, year) %>%
  group_by(year) %>%
  summarise(minister_exits = sum(spell_end), 
            total_ministers = n(), 
            exit_percent = 100*(minister_exits/total_ministers)) %>%
  mutate(type = 'Minister') %>%
  dplyr::select(year, exit_percent, type)



leader_minister_exits <- bind_rows(leader_turnover, minister_turnover)


#Minister turnover only with moving average


ma5 <- data.frame(exit_ma = rollmean(minister_turnover$exit_percent, k = 5),
                  year = 1968:2008)


minister_turnover_ma <- left_join(minister_turnover, ma5) %>%
  #change to long format on exit percentage and exit ma
  pivot_longer(cols = contains('exit')) %>%
  mutate(name = factor(name, levels = c('exit_percent', 'exit_ma')))

#adding moving average for leaders
ma5_leader <- data.frame(exit_ma = rollmean(leader_turnover$exit_percent, k = 5),
                         year = 1968:2008)

leader_turnover_ma <- left_join(leader_turnover, ma5_leader) %>%
  #change to long format on exit percentage and exit ma
  pivot_longer(cols = contains('exit')) %>%
  mutate(name = factor(name, levels = c('exit_percent', 'exit_ma')))




ma_both <- bind_rows(minister_turnover_ma, leader_turnover_ma) %>%
  mutate(group_id = case_when(type=='Minister' & name=='exit_percent' ~ 'Minister Exit Percent', 
                              type == 'Minister' & name=='exit_ma' ~ 'Minister 5yr MA', 
                              type == 'Leader' & name=='exit_percent' ~ 'Leader Exit Percent',
                              type == 'Leader' & name=='exit_ma' ~ 'Leader 5yr MA'))

#Figure A5: Leader and minister exits across GWF SSA sample

ggplot(ma_both, aes(x = year, y = value, linetype = as.factor(name), 
                    color = as.factor(type))) +
  geom_line() +
  scale_linetype_manual(values = c('solid', 'longdash'),
                        labels = c('Yearly Exit Percent', '5yr. Moving Average'), 
                        name = '') +
  scale_color_manual(values = c('black', 'gray60'),
                     name = '') +
  labs(x = 'Year', y =  '% Exiting Position') +
  theme_pubclean() + 
  theme(panel.background = element_rect(fill = 'white'),
        legend.key = element_rect(fill = 'white'),
        legend.title = element_blank(),
        axis.text.x = element_text(angle = 0)) 

ggsave('leader_minister_exits.pdf', 
       width = 6, height = 4)




# Section A8 --------------------------------------------------------------
#Additional placebo tests

#5 year placebo test, conditional logit

placebo_test_5_fe <- function(start_year){
  
  df_placebo <- gwf_ssa %>%
    mutate(time_window = ifelse(year >= start_year & year <= start_year+4, 1, 0)) 
  
  model <- clogit(spell_end ~ time_window + strata(leaderID), 
                  data = df_placebo, 
                  method = 'efron', 
                  cluster = leaderID)
  
  results <- broom::tidy(model) %>%
    dplyr::select(estimate, robust.se)
  
  results 
}


cwe5_placebo_fe <- lapply(start_year, placebo_test_5_fe)

cwe5_placebo_fe_results <- bind_rows(cwe5_placebo_fe) %>%
  mutate(ll = estimate - (1.96*robust.se), 
         ul = estimate + (1.96*robust.se), 
         start_year: 1966:2006,
         window_used = ifelse(start_year==1988, 'Yes', 'No'))

#Figure A6: Five-year window placebo test: CWE coefficients from 
#conditional fixed effects logit model (leader fixed effects)

ggplot(cwe5_placebo_fe_results, aes(x = start_year, y = estimate, 
                                    ymin = ll, ymax = ul,
                                    color = as.factor(window_used))) +
  geom_pointrange(size = .3) + 
  geom_hline(yintercept = 0, linetype = 'dashed') +
  scale_x_continuous(breaks = c(seq(1966, 2006, 1))) +
  scale_color_manual(values = c('gray75', 'black'), 
                     guide_legend('Chosen Window?')) +
  scale_y_continuous(limits = c(-.8, .85), 
                     breaks = c(seq(-.8, .8, .2)), 
                     labels = c(seq(-.8, .8, .2))) +
  labs(x = 'Window Start Year', y = 'Coefficient Estimate') +
  theme_pubclean() +
  theme(text = element_text(size = 12), 
        axis.text.x = element_text(angle = 75, vjust = .4),
        legend.position = 'bottom', 
        legend.key = element_blank())

ggsave('Fig5_CWE5_placebo_fe.pdf', 
       width = 9, height = 6)


#3 year CWE placebo test function

placebo_test_3_pooled <- function(start_year){
  
  df_placebo <- gwf_ssa %>%
    mutate(time_window = ifelse(year >= start_year & year <= start_year+2, 1, 0)) 
  
  model <- glm(spell_end ~ time_window, 
               data = df_placebo, 
               family = binomial)
  
  
  robust_ses <- coeftest(model, cluster.vcov(model, df_placebo$leaderID))
  
  robust_ses <- broom::tidy(robust_ses) %>%
    filter(row_number()==2)
  
  robust_ses
}

start_year3 <- 1966:2008


cwe3_placebo_pooled <- lapply(start_year3, placebo_test_3_pooled)

cwe3_placebo_pooled_results <- lapply(cwe3_placebo_pooled, `[`, c('estimate', 'std.error')) 

cwe3_placebo_pooled_results <- data.frame(matrix(unlist(cwe3_placebo_pooled_results),
                                                 nrow = length(cwe3_placebo_pooled_results), byrow = T)) %>%
  mutate(start_year = 1966:2008, 
         end_year = start_year + 4,
         ul = X1 + (1.96*X2),
         ll = X1 - (1.96*X2)) %>%
  rename(estimate = X1, 
         se = X2)

#Figure A7: Three-year window placebo test: CWE coefficients 

ggplot(cwe3_placebo_pooled_results, aes(x =start_year, y = estimate, 
                                        ymin = ll, ymax = ul)) +
  geom_pointrange(size = .3) + 
  geom_hline(yintercept = 0, linetype = 'dashed') +
  scale_x_continuous(breaks = c(seq(1966, 2008, 1))) +
  scale_y_continuous(limits = c(-.8, 1), 
                     breaks = c(seq(-.8, 1, .2)), 
                     labels = c(seq(-.8, 1, .2))) +
  labs(x = 'Window Start Year', y = 'Coefficient Estimate') +
  theme_pubclean() +
  theme(text = element_text(size = 12), 
        axis.text.x = element_text(angle = 75, vjust = .4),
        legend.position = 'bottom', 
        legend.key = element_blank())

ggsave('Fig5_CWE3_placebo.pdf', 
       width = 9, height = 6)



placebo_test_3_fe <- function(start_year){
  
  df_placebo <- gwf_ssa %>%
    mutate(time_window = ifelse(year >= start_year & year <= start_year+2, 1, 0)) 
  
  model <- clogit(spell_end ~ time_window + strata(leaderID), 
                  data = df_placebo, 
                  method = 'efron', 
                  cluster = leaderID)
  
  results <- broom::tidy(model) %>%
    dplyr::select(estimate, robust.se)
  
  results 
}

cwe3_placebo_fe <- lapply(start_year, placebo_test_3_fe)

cwe3_placebo_fe_results <- bind_rows(cwe3_placebo_fe) %>%
  mutate(ll = estimate - (1.96*robust.se), 
         ul = estimate + (1.96*robust.se), 
         start_year: 1966:2006)

#Figure A8: Three-year window placebo test: CWE coefficients from conditional
#fixed effects logit model (leader fixed effects)

ggplot(cwe3_placebo_fe_results, aes(x = start_year, y = estimate, 
                                    ymin = ll, ymax = ul)) +
  geom_pointrange(size = .3) + 
  geom_hline(yintercept = 0, linetype = 'dashed') +
  scale_x_continuous(breaks = c(seq(1966, 2006, 1))) +
  scale_y_continuous(limits = c(-1.1, .85), 
                     breaks = c(seq(-1, .8, .2)), 
                     labels = c(seq(-1, .8, .2))) +
  labs(x = 'Window Start Year', y = 'Coefficient Estimate') +
  theme_pubclean() +
  theme(text = element_text(size = 12), 
        axis.text.x = element_text(angle = 75, vjust = .4),
        legend.position = 'bottom', 
        legend.key = element_blank())

ggsave('Fig5_CWE3_placebo_fe.pdf', 
       width = 9, height = 6)


# Section A9  -------------------------------------------------------------


#Code above in main text section for Figure 9



# Section A10 -------------------------------------------------------------

# CWE x Oil/Gas Interaction


cwe5_oil <- glm(spell_end ~ CWE_5*ln_oilgas_rents, 
                data = gwf_ssa, 
                family = binomial)

summary(cwe5_oil)

cwe5_oil_se <- sqrt(diag(cluster.vcov(cwe5_oil, gwf_ssa$leaderID)))

#Table A65: Pooled logit model of minister survival interacting
#5-year CWE window with oil and gas rents, GWF SSA sample
stargazer(cwe5_oil,
          se = list(cwe5_oil_se),
          dep.var.labels = 'Minister Exit',
          covariate.labels = c('CWE 5-year', 
                               'ln(Oil/Gas Rents)', 
                               'CWE 5-year X Ln(Oil/Gas Rents)'),
          digits = 2,
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          title = 'Pooled Logit Model of Minister Survival Interacting 5-year CWE Window With Oil and Gas Rents, GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.',
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_oilgas_pooled.tex')



cwe5_oil_fe <- clogit(spell_end ~ CWE_5*ln_oilgas_rents + strata(leaderID), 
                      data = gwf_ssa, 
                      method = 'efron', 
                      cluster = leaderID)

summary(cwe5_oil_fe)

cwe5_oil_fe_results <- broom::tidy(cwe5_oil_fe)

#Table A66: Conditional logit model of minister survival interacting
#5-year CWE window with oil and gas rents, GWF SSA sample
stargazer(cwe5_oil_fe,
          coef = list(cwe5_oil_fe_results$estimate),
          se = list(cwe5_oil_fe_results$robust.se),
          dep.var.labels = 'Minister Exit',
          covariate.labels = c('CWE 5-year', 
                               'ln(Oil/Gas Rents)', 
                               'CWE 5-year X Ln(Oil/Gas Rents)'),
          digits = 2,
          no.space = T,
          omit.stat = c('ll', 'aic', 'rsq', 'max.rsq', 'logrank', 
                        'lr', 'wald'),
          add.lines = list(c('Leader Fixed Effects', 'Yes')),
          title = 'Conditional Logit Model of Minister Survival Interacting 5-year CWE Window With Oil and Gas Rents, GWF SSA Sample', 
          notes = 'Standard errors clustered by leader.',
          star.cutoffs = c(0.05, 0.01, 0.001), 
          out = 'cwe5_oilgas_fe.tex')




# Section A11 -------------------------------------------------------------

# EPR Included Groups DV

cy <- cy %>%
  mutate(PCW = ifelse(year > 1992, 1, 0))

library(estimatr)

#Did the number of groups included in the regime increase postcold war?
epr <- lm_robust(egip_groups_count ~ PCW, 
                 fixed_effects = ~cowcode,
                 data = cy, 
                 clusters = cowcode)

epr_results <- tidy(epr)


# Opposition Parties (#) DV

parties <- lm_robust(parties ~ PCW, 
                     fixed_effects = ~cowcode,
                     data = cy, 
                     clusters = cowcode)

parties_results <- tidy(parties)

# Cabinet Size DV

cabsize <- lm_robust(cabinet_size ~ PCW, 
                     fixed_effects = ~cowcode, 
                     data = cy, 
                     clusters = cowcode)

cabsize_results <- tidy(cabsize)

#Table A67: Fixed effects models of included ethnic groups, 
#included parties, and cabinet size

texreg(list(epr, parties, cabsize), 
       custom.header = list('Dependent variable:' = 1:3),
       custom.model.names = c('\\# Included Ethnic Groups', 
                              '\\# Included Parties',
                              'Cabinet Size'), 
       custom.coef.names = 'Postcold War (1993+)',
       custom.gof.rows = list('Country FE?' = c('Yes', 'Yes', 'Yes')),
       custom.note = 'Standard errors clustered by country. $p < 0.05${*}, $p < 0.01${**}, $p < 0.001${***}',
       caption = 'Fixed Effects Models of Included Ethnic Groups, Included Parties, and Cabinet Size (GWF SSA Sample)',
       caption.above = T,
       include.adjrs = F,
       include.dfresid = F,
       label = 'tab:other_dvs',
       file = 'other_dvs.tex')


# Section A12 -------------------------------------------------------------
#Cabinet plotes by country

triangle_plotter <- function(x){
  
  leader_exits <- x %>%
    group_by(leaderID, year) %>%
    summarise_all(first) %>%
    ungroup() %>%
    filter(leader_exit==1) %>%
    mutate(year = year + .5) 
  
  if(!is.null(leader_exits)){
    
    ggplot() +
      geom_point(data = x, aes(x = year, y = minister_tenure, color = as.factor(spell_end)),
                 position = position_jitter(.1), alpha = .4) +
      scale_color_manual(values = c('gray60', 'red'),
                         name = 'Minister Status:',
                         labels = c('Survived',
                                    'Exited')) +
      labs(x = 'Year', y = 'Minister Tenure') +
      geom_vline(data = leader_exits, aes(xintercept = year),
                 linetype = 'dashed', color = 'gray50') +
      scale_y_continuous(limits = c(0, 30), 
                         breaks = c(seq(0,30,10))) +
      scale_x_continuous(limits = c(1966, 2010),
                         breaks = c(seq(1970,2010, 5))) +
      theme_pubclean() +
      theme(legend.key = element_rect(fill = NA),
            axis.text.x = element_text(angle = 90,
                                       vjust = .5)) +
      ggtitle(paste(x$country_name))
  }
  
  else{ 
    ggplot() +
      geom_point(data = x, aes(x = year, y = minister_tenure, color = as.factor(spell_end)),
                 position = position_jitter(.1), alpha = .4) +
      scale_color_manual(values = c('gray60', 'red'),
                         name = 'Minister Status:',
                         labels = c('Survived',
                                    'Exited')) +
      labs(x = 'Year', y = 'Minister Tenure') +
      scale_y_continuous(limits = c(0, 30), 
                         breaks = c(seq(0,30,10))) +
      scale_x_continuous(limits = c(1966, 2010),
                         breaks = c(seq(1970,2010, 5))) +
      theme_pubclean() +
      theme(legend.key = element_rect(fill = NA), 
            axis.text.x = element_text(angle = 90, 
                                       vjust = .5)) +
      ggtitle(paste(x$country_name))
  }
}



all_triangles <- gwf_ssa %>%
  split(.$cowcode) %>%
  map(., triangle_plotter)

grouped_triangles <- ggarrange(plotlist = all_triangles, 
                               nrow = 2, ncol = 2)

grouped_triangles[[1]]

ggexport(grouped_triangles, filename = 'All_Triangles.pdf')





